package cn.com.connext.scrm.repository.master;


import cn.com.connext.scrm.domain.master.Activity;
import cn.com.connext.scrm.domain.master.Prize;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import java.time.ZonedDateTime;
import java.util.Date;
import java.util.List;

/**
 * Created by YANG205 on 2018/6/27.
 */
@Repository
public interface ActivityRepository extends JpaRepository<Activity, String>, JpaSpecificationExecutor {

    @Query(value = "select a from Activity a where a.isAnswer =false and a.enableFlag=true and a.startTime<current_time and a.endTime>current_time ")
    List<Activity> getCurrentActivity();

    @Query(value = "select a.id from Activity a where a.isAnswer =false and a.enableFlag=true and a.startTime<current_time and a.deadline>current_time ")
    List<String> getAwardStageActivities();

    @Query(value = "select a.* from activity a where a.is_delete=0 and a.is_answer = 1 and a.audit_result =1 and a.enable_flag=1 and a.start_time<now() and a.end_time> now()", nativeQuery = true)
    List<Activity> getCurrentActivityForAnswer();

    @Query(value = "select a.* from activity a WHERE a.is_delete = 0 and a.is_answer = 1 and a.end_time<now() and a.audit_result =1 order by a.end_time desc limit 1", nativeQuery = true)
    Activity getPostActivityForAnswer();

    @Transactional
    @Modifying(clearAutomatically = true)
    @Query(value = " UPDATE activity act left join  whiskey_gifts gift on act.id= gift.activity_id SET act.gift_id = gift.id WHERE act.id = :activityId", nativeQuery = true)
    Integer updateByActivityId(@Param("activityId") String activityId);

    @Query(value = "select a.* from activity a WHERE a.is_delete = 0 and a.is_answer = 1 and a.end_time<now() and a.audit_result =1 order by a.end_time", nativeQuery = true)
    List<Activity> getPostActivityForAnswers();

    Activity findById(String activityId);
}
